<?php

// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件

use OSS\Core\OssException;
use OSS\OssClient;

/**
 * 获取数据库中的配置列表
 * @return array 配置数组
 */
function config_lists(){
    $data   = model('Config')->field('type,name,value')->select();
    $config = array();
    if($data && is_array($data)){
        foreach ($data as $value) {
            $config[$value['name']] = config_parse($value['type'], $value['value']);
        }
    }
    return $config;
}

/**
 * 根据配置类型解析配置
 * @param  integer $type  配置类型
 * @param  string  $value 配置值
 */
function config_parse($type, $value){
    switch ($type) {
        case 3: //解析数组
            $array = preg_split('/[,;\r\n]+/', trim($value, ",;\r\n"));
            if(strpos($value,':')){
                $value  = array();
                foreach ($array as $val) {
                    list($k, $v) = explode(':', $val);
                    $value[$k]   = $v;
                }
            }else{
                $value =    $array;
            }
            break;
    }
    return $value;
}


/**
 * 检测用户是否登录
 * @return integer 0-未登录，大于0-当前登录用户ID
 */
function is_login(){
    $user = session('user_auth');
    if (empty($user)) {
        return 0;
    } else {
        return session('user_auth_sign') == data_auth_sign($user) ? $user['uid'] : 0;
    }
}

/**
 * 系统非常规MD5加密方法
 * @param  string $str 要加密的字符串
 * @return string
 */
function think_ucenter_md5($str, $key='!@#heige123'){
    return '' === $str ? '' : md5(sha1($str) . $key);
    return $str;
}

/**
 * 数据签名认证
 * @param  array  $data 被认证的数据
 * @return string       签名
 */
function data_auth_sign($data) {
    //数据类型检测
    if(!is_array($data)){
        $data = (array)$data;
    }
    ksort($data); //排序
    $code = http_build_query($data); //url编码并生成query字符串
    $sign = sha1($code); //生成签名
    return $sign;
}

/**
 * 记录行为日志，并执行该行为的规则
 */
function action_log($menu_id,$type=1,$url='',$menu='',$uid=0){
    if($menu_id == '' && $menu_id != 0) return;
    if(defined('CONTROLLER_NAME') && strtolower(CONTROLLER_NAME) == 'log') return;
    
    $minfo = db('menu')->find($menu_id);
    $data['type'] = $type;
    $data['mid'] = defined('UID')?UID:$uid;
    $data['menu_id'] = $menu_id;
    $data['ip'] = request()->ip();
    $data['create_time'] = time();
    $data['param'] = json_encode(input('get.'));
    if(!empty($minfo)){
        $data['menu'] = $minfo['title'];
        $data['url'] = url();
    }else{
        $data['menu'] = $menu;
        $data['url'] = url();
    }
    db('action_log')->insert($data);
}

/**
 * 时间戳格式化
 * @param int $time
 * @return string 完整的时间显示
 * @author huajie <banhuajie@163.com>
 */
function time_format($time = NULL,$format='Y-m-d H:i:s'){
    $time = $time === NULL ? NOW_TIME : intval($time);
    return date($format, $time);
}

/**
 * 数据类型转为描述
 * @date: 2018年6月2日 上午11:33:28
 * @author: xiaocui
 * @param: $GLOBALS
 * @return:
 */
function int_to_string(&$data,$map=array('status'=>array(1=>'正常',-1=>'删除',0=>'禁用',2=>'未审核',3=>'草稿'))) {
    if($data === false || $data === null || is_object($data)){
        return $data;
    }
    
    if(is_array($data)){
        foreach ($data as $key => $row){
            foreach ($map as $col=>$pair){
                if(isset($row[$col])){
                    if(isset($pair[$row[$col]])){
                        $data[$key][$col.'_text'] = $pair[$row[$col]];
                    }else{
                        $data[$key][$col.'_text'] = $row[$col];
                    }
                }
            }
        }
        return $data;
    }
    return $data;
}

/**
 * 获取用户组
 * @date: 2017年2月24日 下午7:41:42
 * @author: CUI
 * @param: $GLOBALS
 * @return:
 */
function get_group_field($id,$field='title',$appid=0){
    $skey = 'auth_group_'.$appid;
    if($appid>0){
        $list = cache($skey);
        if($list==null){
            $list = model('AuthGroup')->field('id as group_id,title')->select();
            /* $list1 = M('AgentGroup')->where(array('appid'=>$appid))->select();
             foreach ($list as $key=>$val){
             foreach ($list1 as $k=>$v){
             if($val['group_id'] == $v['group_id']){
             $list[$key]['title'] = $v['title'];
             }
             }
            } */
             
            cache($skey,$list);
        }

        foreach ($list as $val){
            if($id==$val['group_id']){
                return $val[$field];
            }
        }
    }else{
        $list = cache($skey);
        if($list==null){
            $list = model('AuthGroup')->select();
            cache($skey,$list);
        }
        foreach ($list as $val){
            if($id==$val['id']){
                return $val[$field];
            }
        }
    }
}

/**
 * 过滤用户名
 * @date: 2016年12月1日 下午5:49:18
 * @author: CUI
 * @param: $GLOBALS
 * @return:
 */
function filter_uname($str){
    $badstr = config('bad_uname');
    $badstr = explode('|', $badstr);
    if(in_array(strtolower($str), $badstr)){
        return false;
    }else{
        return true;
    }
}

/**
 * 获取管理员信息
 * @date: 2017年3月1日 下午5:07:35
 * @author: CUI
 * @param: $GLOBALS
 * @return:
 */
function get_member_field($id,$field='username'){
    $info = db('member')->find($id);
    if(!empty($info)){
        return $info[$field];
    }
    return '';
}

function get_column_field($id,$field='title'){
    $info = db('column')->find($id);
    if(!empty($info)){
        return $info[$field];
    }
    return '';
}



/**
 +----------------------------------------------------------
 * 字符串截取，支持中文和其他编码
 +----------------------------------------------------------
 * @static
 * @access public
 +----------------------------------------------------------
 * @param string $str 需要转换的字符串
 * @param string $start 开始位置
 * @param string $length 截取长度
 * @param string $charset 编码格式
 * @param string $suffix 截断显示字符
 +----------------------------------------------------------
 * @return string
 +----------------------------------------------------------
 */
function msubstr($str, $start=0, $length, $charset="utf-8", $suffix=true)
{
    $re['utf-8']   = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
    $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
    $re['gbk']    = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
    $re['big5']   = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
    preg_match_all($re[$charset], $str, $match);
    $length_new = $length;
    $length_chi = 0;
    for($i=$start; $i<$length; $i++){
        if (isset($match[0][$i]) && (ord($match[0][$i]) > 0xa0)){
            //中文
        }else{
            $length_new++;
            $length_chi++;
        }
    }
    if($length_chi<$length){
        $length_new = $length+($length_chi/2);
    }
    $slice = join("",array_slice($match[0], $start, $length_new));
    if($suffix && $slice != $str){
        return $slice."…";
    }
    return $slice;
}

/**
 * 获取客户端IP地址
 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @param boolean $adv 是否进行高级模式获取（有可能被伪装）
 * @return mixed
 */
function get_client_ip($type = 0,$adv=false) {
    $type       =  $type ? 1 : 0;
    static $ip  =   NULL;
    if ($ip !== NULL) return $ip[$type];
    if($adv){
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr    =   explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos    =   array_search('unknown',$arr);
            if(false !== $pos) unset($arr[$pos]);
            $ip     =   trim($arr[0]);
        }elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip     =   $_SERVER['HTTP_CLIENT_IP'];
        }elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip     =   $_SERVER['REMOTE_ADDR'];
        }
    }elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip     =   $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u",ip2long($ip));
    $ip   = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}

/**
 * 检查按钮权限
 * @date: 2018年6月15日 上午11:58:25
 * @author: xiaocui
 * @param: $GLOBALS
 * @return:
 */
function chk_btn_auth($id,$rules){
    if(UID == IS_ROOT){
        return true;
    }

    if(empty($rules)){
        return false;
    }

    if(is_array($rules) && in_array($id, $rules)){
        return true;
    }
    return false;
}

/**
 * 下载文件
 * 可以指定下载显示的文件名，并自动发送相应的Header信息
 * 如果指定了content参数，则下载该参数的内容
 * @static
 * @access public
 * @param string $filename 下载文件名
 * @param string $showname 下载显示的文件名
 * @param string $content  下载的内容
 * @param integer $expire  下载内容浏览器缓存时间
 * @return void
 */
function download ($filename, $showname='',$content='',$expire=180) {
    if(is_file($filename)) {
        $length = filesize($filename);
    }elseif(is_file($filename)) {
        $filename = $filename;
        $length = filesize($filename);
    }elseif($content != '') {
        $length = strlen($content);
    }else {
        exit($filename.'下载文件不存在！');
    }
    if(empty($showname)) {
        $showname = $filename;
    }
    $showname = basename($showname);
    /* if(!empty($filename)) {
        $finfo 	= 	new \finfo(FILEINFO_MIME);
        $type 	= 	$finfo->file($filename);
    }else{
        $type	=	"application/octet-stream";
    } */
    $type	=	"application/octet-stream";
    //发送Http Header信息 开始下载
    header("Pragma: public");
    header("Cache-control: max-age=".$expire);
    //header('Cache-Control: no-store, no-cache, must-revalidate');
    header("Expires: " . gmdate("D, d M Y H:i:s",time()+$expire) . "GMT");
    header("Last-Modified: " . gmdate("D, d M Y H:i:s",time()) . "GMT");
    header("Content-Disposition: attachment; filename=".$showname);
    header("Content-Length: ".$length);
    header("Content-type: ".$type);
    header('Content-Encoding: none');
    header("Content-Transfer-Encoding: binary" );
    if($content == '' ) {
        readfile($filename);
    }else {
        echo($content);
    }
    exit();
}


/**
* 生成二维码
* @date: 2018年7月7日 下午3:26:31
* @author: xiaocui
* @param: $GLOBALS
* @return:
*/
function createQRcode($data,$bigImgPath,$size=0,$posx=0,$posy=0){
    $size = $size == 0?450:($size-20);
    $posx = $posx == 0?277:$posx;
    $posy = $posy == 0?1060:$posy;
    
    $dir = 'a'.(UID % 100);
    $save_path =  ROOT_PATH.'public'.DS.'temp'.DS.'qrcode'.DS.$dir.DS;  //图片存储的绝对路径
    $web_path = 'temp/qrcode/'.$dir.'/';        //图片在网页上显示的路径
    
    if(!is_dir($save_path)){
        mkdir($save_path);
    }
    
    $save_path = $save_path.UID.DS;
    $web_path = $web_path.UID.'/';
    
    if(!is_dir($save_path)){
        mkdir($save_path);
    }
    
    $qCodePath = $save_path.md5($data.$size).'.png';
    $savepath = $save_path.md5($data.$bigImgPath.NOW_TIME).".png";
    $web_path = $web_path.md5($data.$bigImgPath.NOW_TIME).".png";
    
    if(!file_exists($qCodePath)){
        $qrCode = new \Endroid\QrCode\QrCode();
        
        $qrCode->setText($data)
        ->setSize($size)
        ->setPadding(10)
        ->setErrorCorrection('high')
        //->setForegroundColor(array('r' =>168, 'g' => 0, 'b' => 168, 'a' => 0))
        ->setImageType('png')
        ->save($qCodePath);
    }
    
    $bigImg = imagecreatefromstring(file_get_contents($bigImgPath));
    $qCodeImg = imagecreatefromstring(file_get_contents($qCodePath));
    list($qCodeWidth, $qCodeHight, $qCodeType) = getimagesize($qCodePath);
    list($bigWidth, $bigHight) = getimagesize($bigImgPath);
    
    // imagecopymerge使用注解
    imagecopymerge($bigImg, $qCodeImg, $posx, $posy, 0, 0, $qCodeWidth, $qCodeHight, 100);
    
    $usermobile = "";
    $yourname = $usermobile;
    
    imagepng($bigImg,$savepath);
    
    return $web_path;
    
}

/**
* 删除目录及文件
* @date: 2018年7月7日 下午4:45:52
* @author: xiaocui
* @param: $GLOBALS
* @return:
*/
function del_dir($dir) {
    if (!is_dir($dir)) {
        return false;
    }
    $handle = opendir($dir);
    while (($file = readdir($handle)) !== false) {
        if ($file != "." && $file != "..") {
            is_dir("$dir/$file") ? del_dir("$dir/$file") : @unlink("$dir/$file");
        }
    }
    if (readdir($handle) == false) {
        closedir($handle);
        //@rmdir($dir);
    }
}

/**
* 发送手机验证码
* @date: 2018年7月9日 下午3:56:34
* @author: xiaocui
* @param: $GLOBALS
* @return:
*/
function send_sms($mobile,$data=''){
    $data = 'mobile='.$mobile.'&templateid='.config('wy_templateid');
    $url = 'https://api.netease.im/sms/sendcode.action';
    $AppKey = config('wy_appkey');
    $AppSecret = config('wy_appsecret');
    $Nonce = md5(NOW_TIME);
    $CurTime = NOW_TIME;
    $CheckSum = sha1($AppSecret.$Nonce.$CurTime);
    
    $header = [
        'Content-type: application/x-www-form-urlencoded',
        'AppKey:'.$AppKey,
        'Nonce:'.$Nonce,
        'CurTime:'.$CurTime,
        'CheckSum:'.$CheckSum
    ];
    
    $opts = array('http' =>
        array(
            'method'  => 'POST',
            'header'  => $header,
            'content' => $data
        )
    );
    
    $context = stream_context_create($opts);
    $res = file_get_contents($url, false, $context);
    //$res = '{"code":200,"msg":"1","obj":"9905"}';
    $res = json_decode($res,true);
    if(is_array($res)){
        if($res['code'] == 200){
            return $res['obj'];
        } else{
            return false;
        }
    }else{
        return false;
    }
}    


/**
* 校验手机验证码
* @date: 2018年7月9日 下午3:58:21
* @author: xiaocui
* @param: $GLOBALS
* @return:
*/
function verify_smscode(){
    $code = session('smscode');
    $time = session('smscode_time');
    $vcode = input('code',0);
    if(empty($code)){
        return false;
    }
    
    if(NOW_TIME > $time+30*600){
        return false;
    }
    
    if($code != $vcode){
        return false;
    }
    return true;
}


/**
* 上传文件到oss
* @date: 2018年7月25日 上午10:06:00
* @author: xiaocui
* @param: $GLOBALS
* @return:
*/
function oss_upload($file){
    try {
        $oss = new OssClient(config('oss_key_id'), config('oss_key_secret'), config('oss_endpoint'));
        $object = basename($file);
        $res = $oss->uploadFile(config('oss_bucket'), $object, $file);
        return ['status'=>1,'url'=>$res['info']['url']];
    } catch (OssException $e) {
        return ['status'=>0,'msg'=>$e->getMessage()];
    }
    
}
    

/**
 * 重新设置url
 * @date: 2018年8月20日 下午6:32:20
 * @author: xiaocui
 * @param: $GLOBALS
 * @return:
 */
function rurl($option = [], $url = '', $vars = '', $suffix = true, $domain = false){
    if($option['type'] == 3){
        return $option['dir'];
    }

    if(config('make_html')==2 || (isset($option['ishtml']) && $option['ishtml']==1)){
        $dir = !empty($option['dir'])?$option['dir']:'html';
        $path = config('web_path').$dir;

        //封面
        if($option['type'] == 1){
            $url = $path.'/index.html';
        }
        //列表
        elseif($option['type'] == 2){
            $page = isset($option['page'])?$option['dir']:1;
            $url = $path.'/list-'.$vars['id'].'-'.$page.'.html';
        }
        //内容
        elseif($option['type'] == 10){
            $url = $path.'/view-'.$vars['id'].'.html';
        }

        return $url;
    }else{
        return url($url, $vars, $suffix, $domain);
    }
}


/**
 * 当前位置
 * @date: 2018年8月21日 下午2:08:02
 * @author: xiaocui
 * @param: $GLOBALS
 * @return:
 */
function get_pos($tid,$data=null){
    if(empty($data)){
        $col = db('column')->field('id,pid,type,title,dir')->where(['display'=>1])->order('id asc')->select();
        import('util.Tree');
        $data = \Tree::getParents($col,$tid,true);
    }

    foreach ($data as $key=>$val){
        $data[$key]['url'] = rurl($val,'lists',['id'=>$val['id']]);
        if(count($data) == $key+1){
            $data[$key]['active'] = 1;
        }else{
            $data[$key]['active'] = 0;
        }
    }
    return $data;
}



   